package cn.gayaguoguo.gritemtags.util;

import java.io.File;
import java.io.InputStreamReader;
import java.io.Reader;

import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.plugin.Plugin;

import com.google.common.base.Charsets;

public class ItemNameUtil {
	
	private static FileConfiguration fileConfiguration = null;
	
	public static void inits(Plugin plugin){
		File configFile = new File(plugin.getDataFolder(), "ItemName.yml");
		if (!configFile.exists()){
			plugin.saveResource("ItemName.yml", false);
		}
		fileConfiguration = YamlConfiguration.loadConfiguration(configFile);
		Reader defConfigStream = new InputStreamReader(plugin.getResource("ItemName.yml"), Charsets.UTF_8);
		if (defConfigStream != null) {
			YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
			fileConfiguration.setDefaults(defConfig);
		}
	}
	
	public static String getChineseName(ItemStack itemStack) {
		Material material = itemStack.getType();
		if (fileConfiguration == null) {
			return material.name();
		}
		try {
			if (material == Material.POTION || material == Material.SPLASH_POTION|| material == Material.LINGERING_POTION || material == Material.TIPPED_ARROW) {
				PotionMeta potionMeta = (PotionMeta) itemStack.getItemMeta();
				try {
					String type = material.name() + ":" + potionMeta.getBasePotionData().getType().name();
					return fileConfiguration.getString(type);	
				} catch (NoSuchMethodError e) {
					if (itemStack.getDurability() == 0){
						return "ˮƿ";
					}
					return "ҩˮ";
				}
			}
		} catch (NoSuchFieldError e) {
			
		}

		String type = material.name();
		String typeDur = material.name() + ":" + itemStack.getDurability();
		if (fileConfiguration.getString(typeDur) != null) {
			return fileConfiguration.getString(typeDur);
		}
		if (fileConfiguration.getString(type) != null) {
			return fileConfiguration.getString(type);
		}
		return typeDur;
	}
}
